<?php
declare (strict_types = 1);

namespace app\model;

use think\facade\Db;
use think\Model;

/**
 * @mixin \think\Model
 */
class Prize extends Model
{

    public  static function draw() {
        $prizes = self::select()->toArray();
        $uids = Db::name('user')->column('id');
        $create_time = date('Y-m-d h:i:s', time());
        foreach ($prizes as $prize) {
            $count = $prize['count'];
            for ($i = 0; $i < $count; $i ++) {
                if(empty($uids)) break;
                $index = self::random($uids);
                $user_id = $uids[$index];
                $prize_id = $prize['id'];
                unset($uids[$index]);
                Db::name('prize_list')->insert(compact('user_id','prize_id','create_time'));
            }
        }
        return Db::name('prize_list')->where('create_time','<>',$create_time)->update(['new' => 0]);
    }
    private static function random($uids) {
        $count = count($uids);
        return random_int(0,$count-1);
    }

    public static function newPrizeList() {
        $sql = "select uname,prize_name,prize from tb_user u ,tb_prize_list up,tb_prize p";
        $sql= $sql. ' ' ."where u.id = up.user_id and up.prize_id = p.id and up.new =:new";
       return Db::query($sql,['new' => 1]);
    }

    public static function prizeList($page = 1,$size =10) {
        $start = ($page - 1) * $size;
        $sql = "select uname,prize_name,prize,create_time,new from tb_user u ,tb_prize_list up,tb_prize p";
        $sql= $sql. ' ' ."where u.id = up.user_id and up.prize_id = p.id order by up.id desc limit :start,:size";
        $list = Db::query($sql,compact('start','size'));
        $total = Db::name('prize_list') ->count();
        return compact('list','total');
    }

}
